package com.steven.ourcontest.forum.view

import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.steven.ourcontest.R
import com.steven.ourcontest.app.AppRouter
import com.steven.ourcontest.base.BaseFragment
import com.steven.ourcontest.forum.adapter.ForumContentViewBinder
import com.steven.ourcontest.forum.bean.ForumContentBean
import com.steven.ourcontest.forum.viewmodel.HotForumViewModel
import kotlinx.android.synthetic.main.hot_forum_fragment.*
import me.drakeet.multitype.Items
import me.drakeet.multitype.MultiTypeAdapter

class HotForumFragment : BaseFragment() {

    private val adapter by lazy {
        MultiTypeAdapter()
    }
    private val item by lazy {
        Items()
    }
    private val forumViewModel: HotForumViewModel by viewModels()
    private var currentPage = 1L

    override fun getViewId(): Int? {
        return R.layout.hot_forum_fragment
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        //refresh
        refresh_container?.setEnableAutoLoadMore(false)
        refresh_container?.setEnableRefresh(true)
        refresh_container?.setRefreshFooter(ClassicsFooter(context))
        refresh_container?.setRefreshHeader(ClassicsHeader(context))
        refresh_container?.setOnRefreshListener {
            currentPage = 1
            forumViewModel.queryHotForumList(currentPage, {
                currentPage++
                refresh_container?.finishRefresh()
            }, {
            })
        }
        refresh_container?.setOnLoadMoreListener {
            forumViewModel.queryHotForumList(currentPage, {
                currentPage++
                refresh_container?.finishLoadMore()
            }, {
            })
        }
        //recyclerView
        container_recycler?.adapter = adapter
        adapter.items = item
        adapter.register(ForumContentBean::class.java, ForumContentViewBinder(context) {
            context?.let { it1 -> AppRouter.startFormDiscussActivity(it1, it) }
        })
        //viewModel
        forumViewModel.hotForumList.observe(viewLifecycleOwner, Observer {
            if (it?.msg == "success") {
                it.list.let { it1 ->
                    item.clear()
                    item.addAll(it1)
                    adapter.notifyDataSetChanged()
                }
            }
        })
        //view
        forumViewModel.queryHotForumList(currentPage, {
            currentPage++
        }, {
        })
    }

}